<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="12">
            <h3>{{ practiceTitle }}</h3>
          </el-col>
          <el-col :span="12" class="text-right">
            <el-button-group>
              <el-button
                type="primary"
                @click="submitPractice"
                :disabled="currentStep !== 1"
              >提交练习</el-button>
              <el-button
                type="info"
                @click="exitPractice"
              >退出练习</el-button>
            </el-button-group>
          </el-col>
        </el-row>
      </div>

      <el-steps :active="currentStep" finish-status="success" simple>
        <el-step title="题目"></el-step>
        <el-step title="作答"></el-step>
        <el-step title="结果"></el-step>
      </el-steps>

      <div class="practice-content">
        <!-- 题目展示步骤 -->
        <div v-if="currentStep === 0" class="step-question">
          <h4>{{ currentQuestion.title }}</h4>
          <formula-renderer class="question-content" :html="currentQuestion.content" />

          <div v-if="currentQuestion.options && currentQuestion.options.length" class="question-options">
            <h5>选项：</h5>
            <el-radio-group
              v-if="currentQuestion.hasOption === 1"
              v-model="form.selectedOptions"
            >
              <el-radio
                v-for="option in currentQuestion.options"
                :key="option.id"
                :label="option.optionCode"
                class="option-item"
              >
                <formula-renderer :html="option.content" />
              </el-radio>
            </el-radio-group>

            <el-checkbox-group
              v-else-if="currentQuestion.hasOption === 2"
              v-model="form.selectedOptions"
            >
              <el-checkbox
                v-for="option in currentQuestion.options"
                :key="option.id"
                :label="option.optionCode"
                class="option-item"
              >
                <formula-renderer :html="option.content" />
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <div v-if="isWrongQuestion" class="question-meta">
            <div class="meta-item">
              <span class="meta-label">来源考试:</span>
              <span class="meta-value">{{ currentRecord.examName }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">错误次数:</span>
              <span class="meta-value">{{ currentRecord.wrongCount }}次</span>
            </div>
          </div>

          <div class="question-actions">
            <el-button type="primary" @click="nextStep">开始作答</el-button>
          </div>
        </div>

        <!-- 作答步骤 -->
        <div v-if="currentStep === 1" class="step-answer">
          <div class="question-display">
            <h4>题目：</h4>
            <formula-renderer class="question-content" :html="currentQuestion.content" />
          </div>

          <h4>请作答:</h4>
          <template v-if="currentQuestion.hasOption">
            <div v-if="currentQuestion.hasOption === 1" class="option-answer">
              <el-radio-group v-model="form.selectedOptions">
                <el-radio
                  v-for="option in currentQuestion.options"
                  :key="option.id"
                  :label="option.optionCode"
                  class="option-item"
                >
                  <formula-renderer :html="option.content" />
                </el-radio>
              </el-radio-group>
            </div>
            <div v-else-if="currentQuestion.hasOption === 2" class="option-answer">
              <el-checkbox-group v-model="form.selectedOptions">
                <el-checkbox
                  v-for="option in currentQuestion.options"
                  :key="option.id"
                  :label="option.optionCode"
                  class="option-item"
                >
                  <formula-renderer :html="option.content" />
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </template>
          <template v-else>
            <wang-editor
              ref="answerEditor"
              v-model="form.answer"
              :mode="'default'"
              style="border: 1px solid #ccc; margin-bottom: 20px;"
            />
          </template>

          <div class="answer-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button type="primary" @click="checkAnswer">提交答案</el-button>
          </div>
        </div>

        <!-- 结果展示步骤 -->
        <div v-if="currentStep === 2" class="step-result">
          <h4>练习结果</h4>

          <div class="result-status">
            <el-alert
              :title="resultStatus.title"
              :type="resultStatus.type"
              :closable="false"
              show-icon
            >
              <span v-if="timeSpent">用时: {{ formatTimeSpent(timeSpent) }}</span>
            </el-alert>
          </div>

          <div class="question-display">
            <h5>题目：</h5>
            <formula-renderer class="question-content" :html="currentQuestion.content" />
          </div>

          <div class="user-answer">
            <h5>你的答案：</h5>
            <template v-if="currentQuestion.hasOption">
              <div v-if="form.selectedOptions && form.selectedOptions.length">
                <p>{{ form.selectedOptions }}</p>
                <div v-for="option in currentQuestion.options"
                     :key="option.id"
                     v-show="form.selectedOptions.includes(option.optionCode)"
                     :class="['option-result', option.isCorrect ? 'correct' : 'incorrect']">
                  <formula-renderer :html="option.content" />
                </div>
              </div>
              <div v-else>
                <el-empty description="未作答" />
              </div>
            </template>
            <template v-else>
              <formula-renderer class="answer-content" :html="form.answer || '未作答'" />
            </template>
          </div>

          <div class="correct-answer" v-if="currentQuestion.answers && currentQuestion.answers.length">
            <h5>正确答案：</h5>
            <template v-if="currentQuestion.hasOption">
              <div v-for="option in currentQuestion.options"
                   :key="option.id"
                   v-show="option.isCorrect"
                   class="correct-option">
                <formula-renderer :html="option.content" />
              </div>
            </template>
            <template v-else>
              <formula-renderer v-for="answer in currentQuestion.answers"
                                :key="answer.id"
                                :html="answer.content" />
            </template>
          </div>

          <div class="question-analysis" v-if="currentQuestion.analysis">
            <h5>题目解析：</h5>
            <formula-renderer :html="currentQuestion.analysis" />
          </div>

          <div class="result-actions">
            <el-button type="primary" @click="nextQuestion">下一题</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getRecordDetail, submitPractice } from '@/api/wrongQuestion'
import { getQuestion } from '@/api/question2/question'
import { formatTime } from '@/utils'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue"
import WangEditor from "@/components/WangEditor/index.vue"

export default {
  name: 'Practice',
  components: {
    FormulaRenderer,
    WangEditor
  },
  data() {
    return {
      // 练习模式: 'wrong'错题练习 | 'recommend'推荐练习 | 'question'普通题目练习
      practiceMode: 'wrong',
      // 练习标题
      practiceTitle: '题目练习',
      // 是否错题练习
      isWrongQuestion: false,
      // 题目ID列表
      questionIds: [],
      currentIndex: 0,
      // 当前步骤
      currentStep: 0,
      // 当前题目
      currentQuestion: {
        title: '',
        content: '',
        analysis: '',
        options: [],
        answers: []
      },
      // 当前错题记录(如果是错题练习)
      currentRecord: null,
      // 表单
      form: {
        answer: '',
        selectedOptions: []
      },
      // 计时器
      startTime: null,
      timeSpent: 0,
      // 结果状态
      resultStatus: {
        title: '',
        type: 'info'
      }
    }
  },
  created() {
    this.initPractice()
  },
  methods: {
    formatTime,

    // 初始化练习
    initPractice() {
      const {recordIds, recordId, questionIds, questionId} = this.$route.query

      if (recordIds || recordId) {
        // 错题练习模式
        this.practiceMode = 'wrong'
        this.practiceTitle = '错题练习'
        this.isWrongQuestion = true

        const ids = recordIds ? recordIds.split(',').map(Number) : [Number(recordId)]
        this.questionIds = ids
        this.loadWrongQuestion(ids[0])
      } else if (questionIds || questionId) {
        // 推荐题目练习模式
        this.practiceMode = 'recommend'
        this.practiceTitle = '推荐题目练习'
        this.isWrongQuestion = false

        const ids = questionIds ? questionIds.split(',').map(Number) : [Number(questionId)]
        this.questionIds = ids
        this.loadQuestion(ids[0])
      } else {
        this.$message.error('缺少练习参数')
        this.exitPractice()
      }

      this.startTime = new Date()
    },

    // 加载错题
    loadWrongQuestion(recordId) {
      getRecordDetail(recordId).then(response => {
        this.currentRecord = response.data
        this.currentQuestion = response.data.question

        // 确保question对象有必要的数组
        this.$set(this.currentQuestion, 'options', this.currentQuestion.options || [])
        this.$set(this.currentQuestion, 'answers', this.currentQuestion.answers || [])
      }).catch(() => {
        this.$message.error('加载错题失败')
        this.exitPractice()
      })
    },

    // 加载普通题目
    loadQuestion(questionId) {
      getQuestion(questionId).then(response => {
        this.currentQuestion = response.data

        // 确保question对象有必要的数组
        this.$set(this.currentQuestion, 'options', this.currentQuestion.options || [])
        this.$set(this.currentQuestion, 'answers', this.currentQuestion.answers || [])

        // 根据题目类型初始化selectedOptions
        if (this.currentQuestion.hasOption === 1) {
          // 单选题初始化为null或空字符串
          this.form.selectedOptions = ''
        } else if (this.currentQuestion.hasOption === 2) {
          // 多选题初始化为空数组
          this.form.selectedOptions = []
        }
      }).catch(() => {
        this.$message.error('加载题目失败')
        this.exitPractice()
      })
    },

    // 下一步
    nextStep() {
      this.currentStep++
    },

    // 上一步
    prevStep() {
      this.currentStep--
    },

    // 检查答案
    checkAnswer() {
      const endTime = new Date()
      this.timeSpent = Math.floor((endTime - this.startTime) / 1000)

      // 计算答案是否正确(仅对选择题)
      let isCorrect = false
      if (this.currentQuestion.hasOption) {
        const correctOptions = this.currentQuestion.options
          .filter(opt => opt.isCorrect)
          .map(opt => opt.optionCode)

        if (this.currentQuestion.hasOption === 1) {
          // 单选题
          isCorrect = this.form.selectedOptions.length === 1 &&
            correctOptions.includes(this.form.selectedOptions[0])
        } else {
          // 多选题
          isCorrect = this.form.selectedOptions.length === correctOptions.length &&
            this.form.selectedOptions.every(opt => correctOptions.includes(opt))
        }

        this.resultStatus = {
          title: isCorrect ? '回答正确!' : '回答错误!',
          type: isCorrect ? 'success' : 'error'
        }
      } else {
        // 主观题无法自动判断对错
        this.resultStatus = {
          title: '已提交作答',
          type: 'info'
        }
      }

      // 如果是错题练习，提交记录
      if (this.isWrongQuestion) {
        this.submitPracticeRecord()
      } else {
        this.currentStep++
      }
    },

    // 提交练习记录(仅错题练习)
    submitPracticeRecord() {
      let answer = ''

      if (this.currentQuestion.hasOption) {
        // 处理选择题答案
        if (this.currentQuestion.hasOption === 1) {
          console.log('A')
          // 单选题
          answer = this.form.selectedOptions || ''
        }
        // else {
        //   console.log('B')
        //   // 多选题
        //   answer = Array.isArray(this.form.selectedOptions)
        //     ? this.form.selectedOptions.join(',')
        //     : ''
        // }
      } else {
        // 主观题答案
        answer = this.form.answer
      }
      console.log('C')

      submitPractice(
        this.currentRecord.id,
        answer,
        this.timeSpent
      ).then(() => {
        this.currentStep++
      }).catch(error => {
        this.$message.error(error.message || '提交答案失败')
      })
    },

    // 下一题
    nextQuestion() {
      this.currentIndex++
      if (this.currentIndex < this.questionIds.length) {
        if (this.practiceMode === 'wrong') {
          this.loadWrongQuestion(this.questionIds[this.currentIndex])
        } else {
          this.loadQuestion(this.questionIds[this.currentIndex])
        }

        this.resetForNextQuestion()
      } else {
        this.$message.success('练习完成!')
        this.exitPractice()
      }
    },

    // 重置为下一题准备
    resetForNextQuestion() {
      this.currentStep = 0
      this.form = {
        answer: '',
        selectedOptions: []
      }
      this.startTime = new Date()
      this.timeSpent = 0
    },

    // 格式化用时显示
    formatTimeSpent(seconds) {
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins > 0 ? `${mins}分` : ''}${secs}秒`
    },

    // 退出练习
    exitPractice() {
      this.$router.go(-1)
    },

    // 提交练习(按钮)
    submitPractice() {
      this.checkAnswer()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.practice-content {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .step-question, .step-answer, .step-result {
    padding: 20px;
  }

  .question-meta {
    margin: 20px 0;
    padding: 10px 0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;

    .meta-item {
      margin-bottom: 5px;
      font-size: 14px;
      color: #666;

      .meta-label {
        font-weight: bold;
        margin-right: 10px;
      }
    }
  }

  .question-options, .option-answer {
    margin: 20px 0;

    .option-item {
      display: block;
      margin: 10px 0;
      padding: 10px;
      border-radius: 4px;
      border: 1px solid #ebeef5;
      white-space: normal;

      ::v-deep .el-radio__label,
      ::v-deep .el-checkbox__label {
        white-space: normal;
      }
    }
  }

  .question-actions, .answer-actions, .result-actions {
    text-align: center;
    margin-top: 30px;
  }

  .question-display, .user-answer, .correct-answer, .question-analysis {
    margin: 20px 0;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;

    h5 {
      margin-top: 0;
      margin-bottom: 10px;
      color: #409eff;
    }
  }

  .user-answer {
    background-color: #f0f9eb;

    .option-result {
      padding: 10px;
      margin: 5px 0;
      border-radius: 4px;

      &.correct {
        background-color: #f0f9eb;
        border: 1px solid #e1f3d8;
      }

      &.incorrect {
        background-color: #fef0f0;
        border: 1px solid #fde2e2;
      }
    }
  }

  .correct-answer {
    background-color: #fef0f0;

    .correct-option {
      padding: 10px;
      margin: 5px 0;
      background-color: #f0f9eb;
      border: 1px solid #e1f3d8;
      border-radius: 4px;
    }
  }

  .result-status {
    margin: 20px 0;
  }
}

.text-right {
  text-align: right;
}

.option-item {
  ::v-deep .el-radio__label,
  ::v-deep .el-checkbox__label {
    display: inline-block;
    vertical-align: middle;
  }
}
</style>
